package com.bdqn.t320.security.controller;


import com.bdqn.t320.security.entity.User;
import com.bdqn.t320.security.service.UserService;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {


    @Resource
    UserService userService;


    @RequestMapping("/")
    public String welcome() {
        return "login";
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

/*    @RequestMapping("/dologin")
    public String dologin(String usrName, String usrPassword, HttpSession session, Model model) {
        User user = userService.findByUsrNameAndUsrPasswordBiz(usrName, usrPassword);
        if (user == null) {
            model.addAttribute("msg", "用户名密码错误");
            //return "redirect:login";
            return "login";
        } else {
            session.setAttribute("user", user);
            return "main";
        }
    }*/

    @RequestMapping("/dologin")
    public String dologin(HttpSession session) {
        //SecurityContext context_session = (SecurityContext) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
        //System.out.println(context_session.getAuthentication().getName());
        SecurityContext context = SecurityContextHolder.getContext();
        //context == context_session  true
        User user = new User();
        user.setUsrName(context.getAuthentication().getName());
        session.setAttribute("user", user);
        return "main";
    }

/*    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        session.invalidate();
        return "redirect:login";
    }*/

    @RequestMapping("/logout")
    public String logout() {
        return "login";
    }

    /**
     * 授权测试页面
     * @return
     */
    @RequestMapping("/user")
    public String user() {
        return "user";
    }

    /**
     * 授权测试页面
     * @return
     */
    @RequestMapping("/admin")
    public String admin() {
        return "admin";
    }
}
